package com.csust.automaticteach.app.teacher.multimodal;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.csust.automaticteach.model.dto.multimodalgen.GenPictureRequest;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @ClassNamePictureGenerateApp
 * @Description 图片生成app
 * @Author钰玟
 * @Date2025/8/5 下午8:00
 * @Version 1.0
 **/
@Service
@Slf4j
public class PictureGenerateApp {
    @Resource
    private MultiModalGenerateConfig multiModalGenerateConfig;


    /**
     * 生成 图片
     *
     * @param request 请求参数
     * @return 图片结果
     */
    public ImageSynthesisResult asyncCall(GenPictureRequest request) {
        log.info("create generate picture task,the request is {}", request.getPrompt());
        String taskId = this.createAsyncTask(request);
        log.info("wait task done then return image url");
        return this.waitAsyncTask(taskId);
    }

    /**
     * 创建异步任务
     *
     * @return taskId
     */
    public String createAsyncTask(GenPictureRequest request) {
        String prompt = String.format("%s,风格：%s", request.getPrompt(), request.getStyle());
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(multiModalGenerateConfig.getApiKey())
                        .model(multiModalGenerateConfig.getTextingPicModel())
                        .prompt(prompt)//提示词
                        .n(request.getCount())//图片数量
                        .size(request.getResolution())//图片分辨率
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        log.info(JsonUtils.toJson(result));
        String taskId = result.getOutput().getTaskId();
        log.info("the pictureGen taskId= {}", taskId);
        return taskId;
    }


    /**
     * 等待异步任务结束
     *
     * @param taskId 任务id
     */
    public ImageSynthesisResult waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.wait(taskId, multiModalGenerateConfig.getApiKey());
        } catch (ApiException | NoApiKeyException e) {
            throw new RuntimeException(e.getMessage());
        }
        log.info("the pictureGen output is {}", JsonUtils.toJson(result.getOutput()));
        return result;
    }


}
